package pers.xiaoliang.concurrency.example.aqs;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @version v1.0
 * @description: 使用CountDownLatch
 * @author: xiaoliang.liu
 * @date: 2018/7/28 21:31
 */
@Slf4j
public class CountDownLatchExample1 {

    private static final int threadCount = 200;


    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newCachedThreadPool();

        final CountDownLatch countDownLatch = new CountDownLatch(threadCount);

        for (int i = 0; i < threadCount; i++) {
            final int threadNum = i;

            executorService.execute(() -> {
                try {
                    test(threadNum);
                } catch (Exception e) {
                    log.info("{}", e);
                } finally {
                    // 计数器减一
                    countDownLatch.countDown();
                }
            });
        }


        // 等待10毫秒，后继续执行代码
        countDownLatch.await(10, TimeUnit.MILLISECONDS);
        log.info("finish");
        executorService.shutdown();
    }


    public static void test(int threadNum) throws InterruptedException {
        Thread.sleep(100);
        log.info("{}", threadNum);
        Thread.sleep(100);
    }
}
